package com.example.villagedevelop.generator.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.villagedevelop.generator.entity.ImagePolicy;
import com.example.villagedevelop.generator.entity.Policy;
import com.example.villagedevelop.generator.entity.PolicyVO;
import com.example.villagedevelop.generator.mapper.ImagePolicyMapper;
import com.example.villagedevelop.generator.mapper.PolicyMapper;
import com.example.villagedevelop.generator.service.ImagePolicyService;
import com.example.villagedevelop.generator.service.PolicyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author villagedevelop
 * @since 2021-11-13
 */
@Service
public class PolicyServiceImpl extends ServiceImpl<PolicyMapper, Policy> implements PolicyService {
    @Autowired
    PolicyMapper mapper;
    @Autowired
    ImagePolicyService service;
    @Autowired
    ImagePolicyMapper imagePolicyMapper;

    @Override
    public List<PolicyVO> findPolicyVOByPage(int current) {
        List<PolicyVO> policyVOList = new ArrayList<>();
        Page<Policy> page = new Page<>(current,5);
        IPage<Policy> result = mapper.selectPage(page,null);
        List<Policy> list = result.getRecords();


        for (Policy ca : list) {
            PolicyVO policyVO = new PolicyVO();
            BeanUtils.copyProperties(ca,policyVO);
            int pid = ca.getId();
            policyVO.setImages(service.getImagesByPid(pid));
            policyVOList.add(policyVO);
        }
        return policyVOList;
    }

    @Override
    public void insertPolicyVO(PolicyVO policyVO) {
        Policy policy = new Policy();
        BeanUtils.copyProperties(policyVO,policy);
        mapper.insert(policy);
        ImagePolicy image = new ImagePolicy();
        int pid = policy.getId();
        for (String url : policyVO.getImages()){
            image.setPId(pid);
            image.setImageFile(url);
            imagePolicyMapper.insert(image);
        }
    }
}
